#include <iostream>
#include "Common.hpp"
#include "InetAddr.hpp"
void Usage(std::string proc)
{
     std::cerr << "Usage: " << proc << " server_ip server_port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 1.创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "sockfd error" << std::endl;
        exit(SOCKET_ERR);
    }
    // 客户端需要bind,但,显示的bind使不需要的
    // 不需要listen,accep,
    // 直接向目标发起连接请求
    InetAddr serveraddr(serverip, serverport);
    int n = connect(sockfd, serveraddr.NetAddrPtr(), serveraddr.NetAddrLen());
    //连接成功,系统自动bind
    if (n < 0)
    {
        perror("error:");
        std::cerr << "connect error" << std::endl;
        exit(CONNECT_ERR);
    }

    while (true)
    {
        std::string line;
        std::cout << "Please Enter@ ";
        getline(std::cin, line);
        write(sockfd, line.c_str(), line.size());
        char buffer[1024];
        ssize_t size = read(sockfd, buffer, sizeof(buffer));
        if (size > 0)
        {
            buffer[size] = 0;
            std::cout << "server echo# " << buffer << std::endl;
        }
    }

    close(sockfd);
    return 0;
}